﻿#include "CustomListItemDelegate.h"
#include "CustomListModel.h"

CustomListItemDelegate::CustomListItemDelegate(QObject *parent)
    : QStyledItemDelegate(parent)
{

}

CustomListItemDelegate::~CustomListItemDelegate()
{

}

QWidget *CustomListItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    Q_UNUSED(option);

    // 获取数据类型
    DataType type = static_cast<DataType>(index.data(Qt::UserRole).toInt());

    switch (type) {
    case IntType: {
        QSpinBox *editor = new QSpinBox(parent);
        const CustomListModel *model = qobject_cast<const CustomListModel*>(index.model());
        if (model) {
            editor->setRange(model->property("intMin").toInt(),
                             model->property("intMax").toInt());
        }
        return editor;
    }
    case ComboType: {
        QComboBox *editor = new QComboBox(parent);
        QStringList items = index.data(Qt::UserRole + 1).value<ComboData>().items;
        editor->addItems(items);
        return editor;
    }
    case BoolType: {
        QCheckBox *editor = new QCheckBox(parent);
        return editor;
    }
    default: // StringType 和其他类型
        return QStyledItemDelegate::createEditor(parent, option, index);
    }
}

void CustomListItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    DataType type = static_cast<DataType>(index.data(Qt::UserRole).toInt());
    QVariant value = index.data(Qt::EditRole);

    switch (type) {
    case IntType:
        qobject_cast<QSpinBox*>(editor)->setValue(value.toInt());
        break;
    case ComboType: {
        QComboBox *combo = qobject_cast<QComboBox*>(editor);
        int idx = index.data(Qt::UserRole + 1).value<ComboData>().currentIndex;
        combo->setCurrentIndex(idx);
        break;
    }
    case BoolType:
        qobject_cast<QCheckBox*>(editor)->setChecked(value.toBool());
        break;
    default:
        QStyledItemDelegate::setEditorData(editor, index);
    }
}

void CustomListItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    DataType type = static_cast<DataType>(index.data(Qt::UserRole).toInt());

    switch (type) {
    case IntType:
        model->setData(index, qobject_cast<QSpinBox*>(editor)->value(), Qt::EditRole);
        break;
    case ComboType: {
        QComboBox *combo = qobject_cast<QComboBox*>(editor);
        model->setData(index, combo->currentIndex(), Qt::EditRole);
        break;
    }
    case BoolType:
        model->setData(index, qobject_cast<QCheckBox*>(editor)->isChecked(), Qt::EditRole);
        break;
    default:
        QStyledItemDelegate::setModelData(editor, model, index);
    }
}

void CustomListItemDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    Q_UNUSED(index);
    editor->setGeometry(option.rect);
}
